package com.waimai.controllor;

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.waimai.log.Log;

@SuppressWarnings("deprecation")
public class HttpControllor extends BaseControllor {

	private static HttpControllor controllor;

	public static HttpControllor getInstance() {
		if (controllor == null) {
			controllor = new HttpControllor();
		}
		return controllor;
	}

	public byte[] getHtmlBytes(URI uri) {
		byte[] bytes = null;
		HttpClient httpClient = null;
		try {
			before();
			httpClient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(uri);
			HttpResponse response = httpClient.execute(httpget);
			int resStatu = response.getStatusLine().getStatusCode();
			// 200是正确的
			after("getConnection");
			if (resStatu != HttpStatus.SC_OK) {
				Log.e("resultCode is not OK");
			}
			if (resStatu == HttpStatus.SC_OK) {
				// 运行时间
				before();
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					// 获得byte
					bytes = EntityUtils.toByteArray(entity);
					// 写到文件里
					// FileOutputStream fos = new
					// FileOutputStream("e:/a.txt");
					// // int off = 0;
					// int length = bytes.length;
					// // while (off <= length) {
					// fos.write(bytes);
					// }
				}
				after("getBytes");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e(e, "urlHasProblem");
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
		return bytes;

	}

}
